import { createRouter, createWebHistory } from 'vue-router'
import routes from '@/router/routes.js'
import { ElMessage } from 'element-plus'
import { loadUserMenus } from '@/api/index.js'

import { useBaseStore } from '@/stores/useBaseStore.js'
import homeConfig from "@/router/homeConfig.js";

let baseStore = null

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

const dynamicRoutesAdded = []

router.beforeEach(async (to, from, next) => {
  if (baseStore === null) {
    baseStore = useBaseStore()
  }
  if (to.meta.isPublic) {
    next()
    return
  }
  if (baseStore.token === '') {
    next('/login')
    ElMessage.error({
      message: '请先登录！！',
    })
  }
  if (baseStore.menus.length === 0) {
    baseStore.menus = await loadUserMenus()
  }
  let needRedirect = false
  for (let m of baseStore.menus) {
    let path=m.right_path;
    let name = path.replace(/^\/home/,"").replace(/^\//g,'')
    if (!dynamicRoutesAdded.includes(name)) {
      let component = homeConfig[path]
      router.addRoute('home',{
        path,
        name,
        component,
      })
      dynamicRoutesAdded.push(name)
      needRedirect = true
    }
  }
  if (needRedirect) {
    next({...to,redirect:true})
  }else {
    next()
  }
})

export default router
